<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Part.1.E.6.containers</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
</head>

<body id="index" class="home">
        <header id="banner" class="body">
                <h1><a href="/">PythonTutorials </a></h1>
                <nav><ul>
                    <li><a href="/category/cpp.html">cpp</a></li>
                    <li class="active"><a href="/category/python.html">python</a></li>
                </ul>
                </nav>
        </header><!-- /#banner -->
<section id="content" class="body">
  <article>
    <header>
      <h1 class="entry-title">
        <a href="/Part.1.E.6.containers.html" rel="bookmark"
           title="Permalink to Part.1.E.6.containers">Part.1.E.6.containers</a></h1>
    </header>

    <div class="entry-content">
<footer class="post-info">
        <span>Mon 06 April 2020</span>
<span>| tags: <a href="/tag/python.html">python</a><a href="/tag/progarmming.html">progarmming</a><a href="/tag/excel.html">Excel</a></span>
</footer><!-- /.post-info -->      <h1>数据容器</h1>
<p>在 Python 中，有个<strong>数据容器</strong>（Container）的概念。</p>
<p>其中包括<strong>字符串</strong>、由 <code>range()</code> 函数生成的<strong>等差数列</strong>、<strong>列表</strong>（List）、<strong>元组</strong>（Tuple）、<strong>集合</strong>（Set）、<strong>字典</strong>（Dictionary）。</p>
<p>这些容器，各有各的用处。其中又分为<em>可变</em>容器（Mutable）和<em>不可变</em>容器（Immutable）。可变的有列表、集合、字典；不可变的有字符串、<code>range()</code> 生成的等差数列、元组。集合，又分为 <em>Set</em> 和 <em>Frozen Set</em>；其中，Set 是<em>可变的</em>，Frozen Set 是<em>不可变的</em>。</p>
<p>字符串、由 <code>range()</code> 函数生成的等差数列、列表、元组是<strong>有序类型</strong>（Sequence Type），而集合与字典是<em>无序</em>的。</p>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/python-containers-final.png?raw=true"></p>
<p>另外，集合没有<em>重合</em>元素。</p>
<h2>迭代（Iterate）</h2>
<p>数据容器里的元素是可以被<strong>迭代的</strong>（Iterable），它们其中包含的元素，可以被逐个访问，以便被处理。</p>
<p>对于数据容器，有一个操作符，<code>in</code>，用来判断某个元素是否属于某个容器。</p>
<p>由于数据容器的可迭代性，再加上这个操作符 <code>in</code>，在 Python 语言里写循环格外容易且方便（以字符串这个字符的容器作为例子）：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="s1">&#39;Python&#39;</span><span class="p">:</span>
  <span class="k">print</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>P
y
t
h
o
n
</pre></div>


<p>在 Python 出现之前，想要完成这样一个访问字符串中的每一个字符的循环，大抵上应该是这样的（比如 C 语言）：</p>
<div class="highlight"><pre><span></span><span class="cp"># Written in C</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">string</span><span class="p">;</span>

<span class="n">scanf</span><span class="p">(</span><span class="s">&quot;%s&quot;</span><span class="p">,</span><span class="n">string</span><span class="p">);</span>
<span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="n">strlen</span><span class="p">(</span><span class="n">string</span><span class="p">);</span>
<span class="kt">int</span> <span class="n">k</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">while</span><span class="p">(</span><span class="n">k</span><span class="o">&lt;</span><span class="n">i</span><span class="p">){</span>
      <span class="n">printf</span><span class="p">(</span><span class="s">&quot;%c&quot;</span><span class="p">,</span> <span class="n">string</span><span class="p">[</span><span class="n">k</span><span class="p">]);</span>
      <span class="n">k</span><span class="o">++</span><span class="p">;</span>
  <span class="p">}</span>
</pre></div>


<p>在 Python 中，简单的 for 循环，只需要指定一个次数就可以了，因为有 range() 这个函数：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
  <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0
1
2
3
4
5
6
7
8
9
</pre></div>


<p>即便是用比 C 更为 “现代” 一点的 JavaScript，也大抵上应该是这样的：</p>
<div class="highlight"><pre><span></span><span class="n">var</span> <span class="n">i</span><span class="p">;</span>
<span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">console</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="p">}</span>
</pre></div>


<p>当然，有时候我们也需要比较复杂的计数器，不过，Python 也不只有 <code>for</code> 循环，还有 <code>while</code> 循环，在必要的时候可以写复杂的计数器。</p>
<h2>列表（List）</h2>
<p>列表和字符串一样，是个<em>有序类型</em>（Sequence Type）的容器，其中包含着有索引编号的元素。</p>
<p>列表中的元素可以是不同类型。不过，在解决现实问题的时候，我们总是倾向于创建由同一个类型的数据构成的列表。遇到由不同类型数据构成的列表，我们更可能做的是想办法把不同类型的数据分门别类地拆分出来，整理清楚 —— 这种工作甚至有个专门的名称与之关联：<em>数据清洗</em>。</p>
<h3>列表的生成</h3>
<p>生成一个列表，有以下几种方式：</p>
<div class="highlight"><pre><span></span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="nb">list</span><span class="p">(),</span> <span class="ow">or</span> <span class="nb">list</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>            <span class="c1"># 这是 Type Casting</span>
<span class="p">[(</span><span class="n">expression</span> <span class="k">with</span> <span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">]</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">,</span> <span class="n">f</span><span class="s1">&#39;has a length of {len(a_list)}.&#39;</span><span class="p">)</span>

<span class="c1">#range() 返回的不是 list，需要用 list() 转换，否则也没办法调用 .append()</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9</span><span class="p">))</span>
<span class="n">b_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">11</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">b_list</span><span class="p">,</span> <span class="n">f</span><span class="s1">&#39;has a length of {len(b_list)}.&#39;</span><span class="p">)</span>

<span class="n">c_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">2</span><span class="o">**</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">,</span> <span class="n">f</span><span class="s1">&#39;has a length of {len(c_list)}.&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[1, 2] has a length of 2.
[1, 2, 3, 4, 5, 6, 7, 8, 11] has a length of 9.
[1, 2, 4, 8, 16, 32, 64, 128] has a length of 8.
</pre></div>


<p>这最后一种方式颇为神奇：</p>
<div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">2</span><span class="o">**</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">)]</span>
</pre></div>


<p>这种做法，叫做 <strong><a href="https://docs.python.org/3.7/tutorial/datastructures.html#tut-listcomps">List Comprehension</a></strong>。</p>
<p><em>Comprehend</em> 这个词的意思除了 “理解” 之外，还有另外一个意思，就是 “包括、囊括” —— 这样的话，你就大概能理解这种做法为什么被称作 <em>List Comprehension</em> 了。中文翻译中，怎么翻译的都有，“列表生成器”、“列表生成式” 等等，都挺好。但是，被翻译成 “列表解析器”，就不太好了，给人的感觉是操作反了……</p>
<p>List comprehension 可以嵌套使用 <code>for</code>，甚至可以加上条件 <code>if</code>。官方文档里有个例子，是用来把两个元素并不完全相同的列表去同后拼成一个列表（下面稍作了改写）：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>

<span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>

<span class="c1"># 生成一个 n 个元素的序列，每个元素是 1~100 之间的随机数</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;a_list comprehends {len(a_list)} random numbers: {a_list}&#39;</span><span class="p">)</span>

<span class="c1"># 从 a_list 里把偶数都挑出来</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a_list</span> <span class="k">if</span> <span class="n">x</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;... and it has {len(b_list)} even numbers: {b_list}&#39;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>a_list comprehends 10 random numbers: [52, 34, 7, 96, 33, 79, 95, 18, 37, 46]
... and it has 5 even numbers: [52, 34, 96, 18, 46]
</pre></div>


<h3>列表的操作符</h3>
<p>列表的操作符和字符串一样，因为它们都是有序容器。列表的操作符有：</p>
<blockquote>
<ul>
<li>拼接：<code>+</code>（与字符串不一样的地方是，不能用空格 <code>' '</code> 了）</li>
<li>复制：<code>*</code></li>
<li>逻辑运算：<code>in</code> 和 <code>not in</code>，<code>&lt;</code>、<code>&lt;=</code>、<code>&gt;</code>、<code>&gt;=</code>、<code>!=</code>、<code>==</code></li>
</ul>
</blockquote>
<p>而后两个列表也和两个字符串一样，可以被比较，即，可以进行逻辑运算；比较方式也跟字符串一样，从两个列表各自的第一个元素开始逐个比较，“一旦决出胜负马上停止”：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="n">c_list</span> <span class="o">=</span> <span class="n">a_list</span> <span class="o">+</span> <span class="n">b_list</span> <span class="o">*</span> <span class="mi">3</span>
<span class="n">c_list</span>
<span class="mi">7</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">c_list</span>
<span class="n">a_list</span> <span class="o">&gt;</span> <span class="n">b_list</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 5, 6]</span>
<span class="na">True</span>
<span class="na">False</span>
</pre></div>


<h3>根据索引提取列表元素</h3>
<p>列表当然也可以根据索引操作，但由于列表是可变序列，所以，不仅可以提取，还可以删除，甚至替换。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">3</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="nb">chr</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">c_list</span> <span class="o">=</span> <span class="n">a_list</span> <span class="o">+</span> <span class="n">b_list</span> <span class="o">+</span> <span class="n">a_list</span> <span class="o">*</span> <span class="mi">2</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>

<span class="k">print</span><span class="p">()</span>
<span class="c1"># 根据索引提取（Slicing）</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">[</span><span class="mi">3</span><span class="p">])</span>        <span class="c1"># 返回索引值为 3 的元素值</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">[:])</span>        <span class="c1"># 相当于 c_list，返回整个列表</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">[</span><span class="mi">5</span><span class="p">:])</span>       <span class="c1"># 从索引为 5 的值开始直到末尾</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">[:</span><span class="mi">3</span><span class="p">])</span>       <span class="c1"># 从索引 0 开始，直到索引 3 之前（不包括 3）</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">6</span><span class="p">])</span>      <span class="c1"># 从索引 2 开始，直到索引 6 之前（不包括 6）</span>

<span class="k">print</span><span class="p">()</span>
<span class="c1"># 根据索引删除</span>
<span class="k">del</span> <span class="n">c_list</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>           <span class="c1"># del 是个命令，del c_list[3] 是一个语句；不能这么写：print(del c_list[3])</span>
<span class="k">del</span> <span class="n">c_list</span><span class="p">[</span><span class="mi">5</span><span class="p">:</span><span class="mi">8</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>

<span class="k">print</span><span class="p">()</span>
<span class="c1"># 根据索引替换</span>
<span class="n">c_list</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">5</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span>  <span class="c1"># s[start:stop:step] = t，跟 range 的三个参数类似；</span>
                         <span class="c1"># len(t) = len([start:stop:step]) 必须为真</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[77, 66, 79]</span>
<span class="k">[77, 66, 79, &#39;L&#39;, &#39;Z&#39;, &#39;R&#39;, 77, 66, 79, 77, 66, 79]</span>

<span class="na">L</span>
<span class="k">[77, 66, 79, &#39;L&#39;, &#39;Z&#39;, &#39;R&#39;, 77, 66, 79, 77, 66, 79]</span>
<span class="k">[&#39;R&#39;, 77, 66, 79, 77, 66, 79]</span>
<span class="k">[77, 66, 79]</span>
<span class="k">[79, &#39;L&#39;, &#39;Z&#39;, &#39;R&#39;]</span>

<span class="k">[77, 66, 79, &#39;Z&#39;, &#39;R&#39;, 77, 66, 79, 77, 66, 79]</span>
<span class="k">[77, 66, 79, &#39;Z&#39;, &#39;R&#39;, 77, 66, 79]</span>

<span class="k">[77, &#39;a&#39;, 79, 2, &#39;R&#39;, 77, 66, 79]</span>
</pre></div>


<p>需要注意的地方是：<strong>列表</strong>（List）是可变序列，而<strong>字符串</strong>（str）是不可变序列，所以，对字符串来说，虽然也可以根据索引提取，但没办法根据索引删除或者替换。</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">del</span> <span class="n">s</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>  <span class="c1"># 这一句会报错</span>
</pre></div>


<div class="highlight"><pre><span></span>tho

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

&lt;ipython-input-7-c9c999709965&gt; in &lt;module&gt;
      1 s = &#39;Python&#39;[2:5]
      2 print(s)
----&gt; 3 del s[3]  # 这一句会报错

TypeError: &#39;str&#39; object doesn&#39;t support item deletion
</pre></div>


<p>之前提到过：</p>
<blockquote>
<p>字符串常量（String Literal）是不可变有序容器，所以，虽然字符串也有一些 Methods 可用，但那些 Methods 都不改变它们自身，而是在操作后返回一个值给另外一个变量。</p>
</blockquote>
<p>而对于列表这种<em>可变容器</em>，我们可以对它进行操作，结果是<em>它本身被改变</em>了。</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="n">L</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="k">del</span> <span class="n">L</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">L</span><span class="p">)</span> <span class="c1"># 用 del 对 L 操作之后，L 本身少了 1 个元素</span>
</pre></div>


<div class="highlight"><pre><span></span>Python
[&#39;P&#39;, &#39;y&#39;, &#39;t&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;]
[&#39;P&#39;, &#39;y&#39;, &#39;h&#39;, &#39;o&#39;, &#39;n&#39;]
</pre></div>


<h3>列表可用的内建函数</h3>
<p>列表和字符串都是容器，它们可使用的内建函数也其实都是一样的：</p>
<blockquote>
<ul>
<li><code>len()</code></li>
<li><code>max()</code></li>
<li><code>min()</code></li>
</ul>
</blockquote>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">3</span>

<span class="c1"># 生成 3 个随机数，构成一个列表</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="nb">chr</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">b_list</span><span class="p">)</span>

<span class="c1"># 列表可以使用操作符 + 和*</span>
<span class="n">c_list</span> <span class="o">=</span> <span class="n">a_list</span> <span class="o">+</span> <span class="n">b_list</span> <span class="o">+</span> <span class="n">a_list</span> <span class="o">*</span> <span class="mi">2</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>

<span class="n">a_list</span> <span class="o">*=</span> <span class="mi">3</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="c1"># 内建函数操作 len()、max()、min()</span>
<span class="k">print</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">c_list</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">b_list</span><span class="p">))</span> <span class="c1"># 内建函数内部做了异常处理，可以比较字符和数字 —— 初学者最讨厌这种事情了……</span>
<span class="k">print</span><span class="p">(</span><span class="nb">min</span><span class="p">(</span><span class="n">b_list</span><span class="p">))</span> <span class="c1"># 注意，max() 和 min() 应用的是 b_list, len() 应用的是 c_list —— 请自行找到对应的 list 进行分析。</span>

<span class="k">print</span><span class="p">(</span><span class="s1">&#39;X&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">b_list</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[89, 84, 85]</span>
<span class="k">[&#39;X&#39;, &#39;B&#39;, &#39;X&#39;]</span>
<span class="k">[89, 84, 85, &#39;X&#39;, &#39;B&#39;, &#39;X&#39;, 89, 84, 85, 89, 84, 85]</span>
<span class="k">[89, 84, 85, 89, 84, 85, 89, 84, 85]</span>
<span class="na">12</span>
<span class="na">X</span>
<span class="na">B</span>
<span class="na">False</span>
</pre></div>


<h3>Methods</h3>
<p>字符串常量和 range() 都是不可变的（Immutable）；而列表则是<strong>可变类型</strong>（Mutable type），所以，它最起码可以被排序 —— 使用 <code>sort()</code> Method：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;a_list comprehends {len(a_list)} random numbers:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">a_list</span><span class="p">)</span>

<span class="n">a_list</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;the list sorted:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">a_list</span><span class="p">)</span>

<span class="n">a_list</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="c1">#reverse 参数，默认是 False</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;the list sorted reversely:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">a_list</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>a_list comprehends 10 random numbers:
 [98, 9, 95, 15, 80, 70, 98, 82, 88, 46]
the list sorted:
 [9, 15, 46, 70, 80, 82, 88, 95, 98, 98]
the list sorted reversely:
 [98, 98, 95, 88, 82, 80, 70, 46, 15, 9]
</pre></div>


<p>如果列表中的元素全都是由字符串构成的，当然也可以排序：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>

<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="nb">chr</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="c1"># chr() 函数会返回指定 ascii 码的字符，ord(&#39;A&#39;) 是 65</span>
<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;a_list comprehends {len(a_list)} random string elements:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">a_list</span><span class="p">)</span>

<span class="n">a_list</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;the list sorted:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">a_list</span><span class="p">)</span>

<span class="n">a_list</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="c1">#reverse 参数，默认是 False</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;the list sorted reversely:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">a_list</span><span class="p">)</span>

<span class="k">print</span><span class="p">()</span>

<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="nb">chr</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">))</span> <span class="o">+</span>\
            <span class="nb">chr</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">97</span><span class="p">,</span> <span class="mi">123</span><span class="p">))</span>\
            <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="c1"># 可以在行末加上 \ 符号，表示 “该行未完待续……”</span>

<span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">&#39;b_list comprehends {len(b_list)} random string elements:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">b_list</span><span class="p">)</span>

<span class="n">b_list</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;the sorted:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">b_list</span><span class="p">)</span>

<span class="n">b_list</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="nb">str</span><span class="o">.</span><span class="n">lower</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="c1"># key 参数，默认是 None</span>
<span class="c1"># key=str.lower 的意思是，在比较排序的时候，先全都转换成小写再比较排序……</span>
<span class="c1"># —— 但并不改变原有值</span>
<span class="k">print</span><span class="p">(</span><span class="s1">&#39;the sorted reversely:</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">b_list</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>a_list comprehends 10 random string elements:
 [&#39;B&#39;, &#39;U&#39;, &#39;H&#39;, &#39;D&#39;, &#39;C&#39;, &#39;V&#39;, &#39;V&#39;, &#39;Q&#39;, &#39;U&#39;, &#39;P&#39;]
the list sorted:
 [&#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;H&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;U&#39;, &#39;U&#39;, &#39;V&#39;, &#39;V&#39;]
the list sorted reversely:
 [&#39;V&#39;, &#39;V&#39;, &#39;U&#39;, &#39;U&#39;, &#39;Q&#39;, &#39;P&#39;, &#39;H&#39;, &#39;D&#39;, &#39;C&#39;, &#39;B&#39;]

b_list comprehends 10 random string elements:
 [&#39;Nl&#39;, &#39;Mh&#39;, &#39;Ta&#39;, &#39;By&#39;, &#39;Ul&#39;, &#39;Nc&#39;, &#39;Gu&#39;, &#39;Rp&#39;, &#39;Pv&#39;, &#39;Bu&#39;]
the sorted:
 [&#39;Bu&#39;, &#39;By&#39;, &#39;Gu&#39;, &#39;Mh&#39;, &#39;Nc&#39;, &#39;Nl&#39;, &#39;Pv&#39;, &#39;Rp&#39;, &#39;Ta&#39;, &#39;Ul&#39;]
the sorted reversely:
 [&#39;Ul&#39;, &#39;Ta&#39;, &#39;Rp&#39;, &#39;Pv&#39;, &#39;Nl&#39;, &#39;Nc&#39;, &#39;Mh&#39;, &#39;Gu&#39;, &#39;By&#39;, &#39;Bu&#39;]
</pre></div>


<p><strong>注意</strong>：不能乱比较…… 被比较的元素应该是同一类型 —— 所以，不是由同一种数据类型元素构成的列表，不能使用 <code>sort()</code> Method。下面的代码会报错：</p>
<div class="highlight"><pre><span></span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">]</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="n">a_list</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="c1"># 这一句会报错</span>
</pre></div>


<div class="highlight"><pre><span></span>---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

&lt;ipython-input-12-acb9480a455d&gt; in &lt;module&gt;
      1 a_list = [1, &#39;a&#39;, &#39;c&#39;]
----&gt; 2 a_list = a_list.sort() # 这一句会报错

TypeError: &#39;&lt;&#39; not supported between instances of &#39;str&#39; and &#39;int&#39;
</pre></div>


<p><strong>可变序列</strong>还有一系列可用的 <strong>Methods</strong>：<code>a.append()</code>，<code>a.clear()</code>，<code>a.copy()</code>，<code>a.extend(t)</code>，<code>a.insert(i，x)</code>，<code>a.pop([i])</code>，<code>a.remove(x)</code>，<code>a.reverse()</code>……</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">3</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="n">b_list</span> <span class="o">=</span> <span class="p">[</span><span class="nb">chr</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">c_list</span> <span class="o">=</span> <span class="n">a_list</span> <span class="o">+</span> <span class="n">b_list</span> <span class="o">+</span> <span class="n">a_list</span> <span class="o">*</span> <span class="mi">2</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>

<span class="c1"># 在末尾追加一个元素</span>
<span class="n">c_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;100&#39;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>

<span class="c1"># 清空序列</span>
<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="k">print</span><span class="p">()</span>
<span class="c1"># 拷贝一个列表</span>
<span class="n">d_list</span> <span class="o">=</span> <span class="n">c_list</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">d_list</span><span class="p">)</span>
<span class="k">del</span> <span class="n">d_list</span><span class="p">[</span><span class="mi">6</span><span class="p">:</span><span class="mi">8</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">d_list</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>             <span class="c1"># 对一个拷贝操作，不会更改 “原件”</span>

<span class="k">print</span><span class="p">()</span>
<span class="c1"># 演示拷贝 .copy() 与赋值 = 的不同</span>
<span class="n">e_list</span> <span class="o">=</span> <span class="n">d_list</span>
<span class="k">del</span> <span class="n">e_list</span><span class="p">[</span><span class="mi">6</span><span class="p">:</span><span class="mi">8</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">e_list</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">d_list</span><span class="p">)</span>             <span class="c1"># 对 e_list 操作，相当于对 d_list 操作</span>

<span class="c1"># 在末尾追加一个列表</span>
<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">c_list</span><span class="p">)</span>      <span class="c1"># 相当于 a_list += c_list</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="c1"># 在某索引位置插入一个元素</span>
<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;example&#39;</span><span class="p">)</span>   <span class="c1"># 在索引 1 的位置插入 &#39;example&#39;</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;example&#39;</span><span class="p">)</span>   <span class="c1"># 在索引 3 的位置插入 &#39;example&#39;；</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="c1"># 排序</span>

<span class="c1"># a_list.sort() 这一句会出错，因为当前列表中的元素，是 int 和 str 混合的。</span>

<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">a_list</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span> <span class="c1"># reverse() 只对当前序列操作，并不返回一个逆序列表；返回值是 None</span>
<span class="k">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[90, 88, 73]</span>
<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73]</span>
<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>

<span class="k">[90, 88, 73]</span>
<span class="k">[]</span>

<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>
<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 73, 90, 88, 73, &#39;100&#39;]</span>
<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>

<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 88, 73, &#39;100&#39;]</span>
<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 88, 73, &#39;100&#39;]</span>

<span class="k">[]</span>
<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>

<span class="k">[90, 88, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>
<span class="k">[90, &#39;example&#39;, 88, &#39;example&#39;, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>

<span class="k">[90, &#39;example&#39;, 88, &#39;example&#39;, 73, &#39;T&#39;, &#39;N&#39;, &#39;Y&#39;, 90, 88, 73, 90, 88, 73, &#39;100&#39;]</span>
<span class="k">[&#39;100&#39;, 73, 88, 90, 73, 88, 90, &#39;Y&#39;, &#39;N&#39;, &#39;T&#39;, 73, &#39;example&#39;, 88, &#39;example&#39;, 90]</span>
<span class="na">None</span>
</pre></div>


<p>有一个命令、两个 Methods 与删除单个元素相关联，<code>del</code>，<code>a.pop([i])</code>，<code>a.remove(x)</code>，请注意它们之间的区别。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">3</span>
<span class="n">a_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">65</span><span class="p">,</span> <span class="mi">91</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="c1"># 插入</span>
<span class="k">print</span><span class="p">()</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;example&#39;</span><span class="p">)</span>   <span class="c1"># 在索引 1 的位置插入 &#39;example&#39;</span>

<span class="c1"># 删除</span>
<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;example&#39;</span><span class="p">)</span>      <span class="c1"># 去除 &#39;example&#39; 这个元素，如果有多个 &#39;example&#39;，只删除第一个</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="c1"># pop() 删除并返回被删除的值</span>

<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">a_list</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>      <span class="c1"># 去除索引为 2 的元素，且返回元素的值，赋值给 p</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">p</span><span class="p">)</span>

<span class="c1"># pop() 与 del，或者 remove() 的区别</span>
<span class="k">print</span><span class="p">()</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;example&#39;</span><span class="p">)</span>
<span class="n">a_list</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;example&#39;</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
<span class="k">del</span> <span class="n">a_list</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>

<span class="k">print</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;example&#39;</span><span class="p">))</span> <span class="c1"># a_list.remove() 这个 Method 的返回值是 None</span>
<span class="k">print</span><span class="p">(</span><span class="n">a_list</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[88, 84, 69]</span>

<span class="k">[88, &#39;example&#39;, 84, 69]</span>
<span class="k">[88, 84, 69]</span>

<span class="k">[88, 84, 69]</span>
<span class="k">[88, 84]</span>
<span class="na">69</span>

<span class="k">[88, 84, &#39;example&#39;, &#39;example&#39;]</span>
<span class="k">[88, 84, &#39;example&#39;]</span>

<span class="na">None</span>
<span class="k">[88, 84]</span>
</pre></div>


<h3>小结</h3>
<p>看起来是个新概念，例子全部读完也很是要花上一段时间，然而，从操作上来看，操作列表和操作字符串的差异并不大，重点在于一个是 Immutable，另外一个是 Mutable，所以，例如像 <code>a.sort()</code>，<code>a.remove()</code> 这样的事，列表能做，字符串不能做 —— 字符串也可以排序，但那是排序之后返回给另外一个变量；而列表可以直接改变自身……</p>
<p>而整理成表格之后呢，理解与记忆真的是零压力：</p>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/list-concepts.png?raw=true"></p>
<h2>元组（Tuple）</h2>
<p>在完整掌握列表的创建与操作之后，再理解元组（Tuple）就容易了，因为它们之间的主要区别只有两个：</p>
<blockquote>
<ul>
<li>List 是<em>可变</em>有序容器，Tuple 是<em>不可变</em>有序容器。</li>
<li>List 用<em>方括号</em>标识 <code>[]</code>，Tuple 用<em>圆括号</em> 标识 <code>()</code>。</li>
</ul>
</blockquote>
<p>创建一个元组的时候，用圆括号：</p>
<div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="p">()</span>
</pre></div>


<p>这样就创建了一个空元组。</p>
<p>多个元素之间，用 <code>,</code> 分离。</p>
<p>创建一个含多个元素的元组，可以省略这个括号。</p>
<div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span>   <span class="c1"># 不建议这种写法</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="c1"># 在创建元组的时候建议永远不省略圆括号……</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="n">a</span> <span class="o">==</span> <span class="n">b</span>
</pre></div>


<div class="highlight"><pre><span></span>(1, 2, 3)
(1, 2, 3)
True
</pre></div>


<p><strong>注意</strong>：创建单个元素的元组，无论是否使用圆括号，在那唯一的元素后面一定要<em>补上一个逗号</em> <code>,</code>：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">a</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span> <span class="c1"># 注意这个末尾的逗号 , 它使得 a 变量被定义为一个元组，而不是数字</span>
<span class="n">a</span>

<span class="n">b</span> <span class="o">=</span> <span class="mi">2</span>  <span class="c1"># 整数，赋值</span>
<span class="n">b</span>

<span class="n">c</span> <span class="o">=</span> <span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="c1"># 不是元组</span>
<span class="n">c</span>
<span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># 还是 int</span>

<span class="n">d</span> <span class="o">=</span> <span class="p">(</span><span class="mi">2</span><span class="p">,)</span> <span class="c1"># 这才是元组</span>
<span class="n">d</span>
<span class="n">a</span> <span class="o">==</span> <span class="n">d</span>
</pre></div>


<div class="highlight"><pre><span></span>(2,)
2
2
int
(2,)
True
</pre></div>


<p>元组是不可变序列，所以，你没办法从里面删除元素。</p>
<p>但是，你可以在末尾追加元素。所以，严格意义上，对元组来讲，“不可变” 的意思是说，“<strong>当前已有部分不可变</strong>”……</p>
<div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">))</span>
<span class="n">a</span> <span class="o">+=</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span>
<span class="k">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">))</span> <span class="c1"># id 并不相同 —— 实际上是在内存中另外新创建了一个元组……</span>
</pre></div>


<div class="highlight"><pre><span></span>(1,)
4593032496
(1, 3, 5)
4592468976
</pre></div>


<p>初学者总是很好奇 List 和 Tuple 的区别。首先是使用场景，在将来需要更改的时候，创建 List
；在将来不需要更改的时候，创建 Tuple。其次，从计算机的角度来看，Tuple 相对于 List 占用更小的内存。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">n</span> <span class="o">=</span> <span class="mi">10000</span> <span class="c1">#@param {type:&quot;number&quot;}</span>
<span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="c1"># 把 a 转换成元组</span>
<span class="n">c</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="c1"># 把 a 转换成列表</span>
<span class="n">a</span><span class="o">.</span><span class="n">__sizeof__</span><span class="p">()</span>
<span class="n">b</span><span class="o">.</span><span class="n">__sizeof__</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">__sizeof__</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>48

80024

90088
</pre></div>


<p>等你了解了 Tuple 的标注方式，你就会发现，<code>range()</code> 函数返回的等差数列就是一个 Tuple —— <code>range(6)</code> 就相当于 <code>(0, 1, 2, 3, 4, 5)</code>。</p>
<h2>集合（Set）</h2>
<p><strong>集合</strong>（Set）这个容器类型与列表不同的地方在于，首先它<em>不包含重合元素</em>，其次它是<em>无序</em>的；进而，集合又分为两种，Set，<em>可变的</em>，Frozen Set，<em>不可变的</em>。</p>
<p>创建一个集合，用<strong>花括号</strong> <code>{}</code> 把元素括起来，用 <code>,</code> 把元素隔开：</p>
<div class="highlight"><pre><span></span><span class="n">primes</span> <span class="o">=</span> <span class="p">{</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">17</span><span class="p">}</span>
<span class="n">primes</span>
</pre></div>


<div class="highlight"><pre><span></span>{2, 3, 5, 7, 11, 13, 17}
</pre></div>


<h3>创建</h3>
<p>注意：创建空集合的时候，必须用 <code>set()</code>，而不能用 <code>{}</code>:</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">a</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># 注意这样创建的是一个 dict（字典），而不是 set 集合</span>
<span class="n">b</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span> <span class="c1"># 这样创建的才是空集合</span>
<span class="nb">type</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="nb">type</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>dict
set
</pre></div>


<p>也可以将序列数据转换（Casting）为集合。转换后，返回的是一个已<strong>去重</strong>的集合。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;abcabcdeabcdbcdef&quot;</span>
<span class="n">b</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="n">c</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
<span class="n">d</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="nb">set</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="nb">set</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="nb">set</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3}
{&#39;a&#39;, &#39;b&#39;, &#39;e&#39;}
</pre></div>


<p>Set 当然也可以进行 <em>Comprehension</em>：</p>
<div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;abcabcdeabcdbcdef&quot;</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span> <span class="k">if</span> <span class="n">x</span> <span class="ow">not</span> <span class="ow">in</span> <span class="s1">&#39;abc&#39;</span><span class="p">}</span>
<span class="n">b</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;d&#39;, &#39;e&#39;, &#39;f&#39;}
</pre></div>


<h3>操作</h3>
<p>将序列类型数据转换成 Set，就等于<strong>去重</strong>。当然，也可以用 <code>in</code> 来判断某个元素是否属于这个集合。<code>len()</code>、<code>max()</code>、<code>min()</code>，也都可以用来操作 Set，但 <code>del</code> 却不行 —— 因为 Set 中的元素没有索引（它不是有序容器）。从 Set 里删除元素，得用 <code>set.remove(elem)</code>；而 Frozen Set 是不可变的，所以不能用 <code>set.remove(elem)</code> 操作。</p>
<p>对于集合，有相应的操作符可以对它们进行集合运算：</p>
<blockquote>
<ul>
<li>并集：<code>|</code></li>
<li>交集：<code>&amp;</code></li>
<li>差集：<code>-</code></li>
<li>对称差集：<code>^</code></li>
</ul>
</blockquote>
<p>之前用 <code>set('abcabcdeabcdbcdef')</code> 作为简单例子还凑合能用；但这样对读者无意义的集合，无助于进一步的理解。</p>
<p>事实上，每种数据结构（Data Structures —— 在这一章里，我们一直用的概念是 “容器”，其实是指同一事物的两种称呼）都有自己的应用场景。比如，当我们需要管理很多用户时，集合就可以派上很大用场。</p>
<p>假定两个集合中有些人是 admins，有些人是 moderators：</p>
<div class="highlight"><pre><span></span><span class="n">admins</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">}</span>
<span class="n">moderators</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Ann&#39;</span><span class="p">,</span> <span class="s1">&#39;Chris&#39;</span><span class="p">,</span> <span class="s1">&#39;Jane&#39;</span><span class="p">,</span> <span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Zero&#39;</span><span class="p">}</span>
</pre></div>


<p>那么：</p>
<div class="highlight"><pre><span></span><span class="n">admins</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">}</span>
<span class="n">moderators</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Ann&#39;</span><span class="p">,</span> <span class="s1">&#39;Chris&#39;</span><span class="p">,</span> <span class="s1">&#39;Jane&#39;</span><span class="p">,</span> <span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Zero&#39;</span><span class="p">}</span>

<span class="n">admins</span>                 <span class="c1"># 去重自动完成</span>
<span class="s1">&#39;Joker&#39;</span> <span class="ow">in</span> <span class="n">admins</span>      <span class="c1"># Joker 是否是 admins？</span>
<span class="s1">&#39;Joker&#39;</span> <span class="ow">in</span> <span class="n">moderators</span>  <span class="c1"># Joker 是否是 moderator？</span>
<span class="n">admins</span> <span class="o">|</span> <span class="n">moderators</span>    <span class="c1"># admins、moderator，或者身兼两职的，即，两个角色中的所有人 in admins or moderators or both</span>
<span class="n">admins</span> <span class="o">&amp;</span> <span class="n">moderators</span>    <span class="c1"># 既是 admins 又是 moderator 的都有谁？in both admins and moderators</span>
<span class="n">admins</span> <span class="o">-</span> <span class="n">moderators</span>    <span class="c1"># 是 admins 但不是 moderator 的都有谁？in admins but not in moderators</span>
<span class="n">admins</span> <span class="o">^</span> <span class="n">moderators</span>    <span class="c1"># admins 和 moderator 中不是身兼两职的都有谁？in admins or moderator but not both</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;Joker&#39;, &#39;Moose&#39;}
True
False
{&#39;Ann&#39;, &#39;Chris&#39;, &#39;Jane&#39;, &#39;Joker&#39;, &#39;Moose&#39;, &#39;Zero&#39;}
{&#39;Moose&#39;}
{&#39;Joker&#39;}
{&#39;Ann&#39;, &#39;Chris&#39;, &#39;Jane&#39;, &#39;Joker&#39;, &#39;Zero&#39;}
</pre></div>


<div class="highlight"><pre><span></span><span class="c1"># 这个 cell 集合运算图示需要安装 matplotlib 和 matplotlib-venn</span>
<span class="c1"># !pip install matplotlib</span>
<span class="c1"># !pip install matplotlib-venn</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>
<span class="kn">from</span> <span class="nn">matplotlib_venn</span> <span class="kn">import</span> <span class="n">venn2</span>

<span class="n">admins</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">}</span>
<span class="n">moderators</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Ann&#39;</span><span class="p">,</span> <span class="s1">&#39;Chris&#39;</span><span class="p">,</span> <span class="s1">&#39;Jane&#39;</span><span class="p">,</span> <span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Zero&#39;</span><span class="p">}</span>

<span class="n">v</span> <span class="o">=</span> <span class="n">venn2</span><span class="p">(</span><span class="n">subsets</span><span class="o">=</span><span class="p">(</span><span class="n">admins</span><span class="p">,</span> <span class="n">moderators</span><span class="p">),</span> <span class="n">set_labels</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;admins&#39;</span><span class="p">,</span> <span class="s1">&#39;moderators&#39;</span><span class="p">))</span>
<span class="n">v</span><span class="o">.</span><span class="n">get_label_by_id</span><span class="p">(</span><span class="s1">&#39;11&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">set_text</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">admins</span> <span class="o">&amp;</span> <span class="n">moderators</span><span class="p">))</span>
<span class="n">v</span><span class="o">.</span><span class="n">get_label_by_id</span><span class="p">(</span><span class="s1">&#39;10&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">set_text</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">admins</span> <span class="o">-</span> <span class="n">moderators</span><span class="p">))</span>
<span class="n">v</span><span class="o">.</span><span class="n">get_label_by_id</span><span class="p">(</span><span class="s1">&#39;01&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">set_text</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">moderators</span> <span class="o">-</span> <span class="n">admins</span><span class="p">))</span>

<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>


<p><img alt="png" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/Part.1.E.6.containers_66_0.png?raw=true"></p>
<p>以上的操作符，都有另外一个版本，即，用 Set 这个类的 Methods 完成。</p>
<table>
<thead>
<tr>
<th align="center">意义</th>
<th align="center">操作符</th>
<th align="center">Methods</th>
<th align="center">Methods 相当于</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">并集</td>
<td align="center"><code>&#124;</code></td>
<td align="center"><code>set.union(*others)</code></td>
<td align="center"><code>set &#124; other &#124; ...</code></td>
</tr>
<tr>
<td align="center">交集</td>
<td align="center"><code>&amp;</code></td>
<td align="center"><code>set.intersection(*others)</code></td>
<td align="center"><code>set &amp; other &amp; ...</code></td>
</tr>
<tr>
<td align="center">差集</td>
<td align="center"><code>-</code></td>
<td align="center"><code>set.difference(*others)</code></td>
<td align="center"><code>set - other - ...</code></td>
</tr>
<tr>
<td align="center">对称差集</td>
<td align="center"><code>^</code></td>
<td align="center"><code>set.symmetric_difference(other)</code></td>
<td align="center"><code>set ^ other</code></td>
</tr>
</tbody>
</table>
<p>注意，并集、交集、差集的 Methods，可以接收多个集合作为参数 <code>(*other)</code>，但对称差集 Method 只接收一个参数 <code>(other)</code>。</p>
<p>对于集合，推荐更多使用 Methods 而不是操作符的主要原因是：更易读 —— 对人来说，因为有意义、有用处的代码终将需要人去维护。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">admins</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">,</span> <span class="s1">&#39;Joker&#39;</span><span class="p">}</span>
<span class="n">moderators</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Chris&#39;</span><span class="p">,</span> <span class="s1">&#39;Moose&#39;</span><span class="p">,</span> <span class="s1">&#39;Jane&#39;</span><span class="p">,</span> <span class="s1">&#39;Zero&#39;</span><span class="p">}</span>

<span class="n">admins</span><span class="o">.</span><span class="n">union</span><span class="p">(</span><span class="n">moderators</span><span class="p">)</span>
<span class="n">admins</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">moderators</span><span class="p">)</span>
<span class="n">admins</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="n">moderators</span><span class="p">)</span>
<span class="n">admins</span><span class="o">.</span><span class="n">symmetric_difference</span><span class="p">(</span><span class="n">moderators</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;Chris&#39;, &#39;Jane&#39;, &#39;Joker&#39;, &#39;Moose&#39;, &#39;Zero&#39;}
{&#39;Moose&#39;}
{&#39;Joker&#39;}
{&#39;Chris&#39;, &#39;Jane&#39;, &#39;Joker&#39;, &#39;Zero&#39;}
</pre></div>


<h3>逻辑运算</h3>
<p>两个集合之间可以进行逻辑比较，返回布尔值。</p>
<p><strong>set</strong> <code>==</code> <strong>other</strong></p>
<blockquote>
<p><code>True</code>: set 与 other 相同</p>
</blockquote>
<p><strong>set</strong> <code>!=</code> <strong>other</strong></p>
<blockquote>
<p><code>True</code>: set 与 other 不同</p>
</blockquote>
<p><strong>isdisjoint</strong>(<em>other</em>)</p>
<blockquote>
<p><code>True</code>: set 与 other 非重合；即，<code>set &amp; other == None</code></p>
</blockquote>
<p><strong>issubset</strong>(<em>other</em>)，<strong>set</strong> <code>&lt;=</code> <strong>other</strong></p>
<blockquote>
<p><code>True</code>: set 是 other 的子集</p>
</blockquote>
<p><strong>set</strong> <code>&lt;</code> <strong>other</strong></p>
<blockquote>
<p><code>True</code>: set 是 other 的真子集，相当于 <code>set &lt;= other &amp;&amp; set != other</code></p>
</blockquote>
<p><strong>issuperset</strong>(<em>other</em>)，<strong>set</strong> <code>&gt;=</code> <strong>other</strong></p>
<blockquote>
<p><code>True</code>: set 是 other 的超集</p>
</blockquote>
<p><strong>set</strong> <code>&gt;</code> <strong>other</strong></p>
<blockquote>
<p><code>True</code>: set 是 other 的真超集，相当于 <code>set &gt;= other &amp;&amp; set != other</code></p>
</blockquote>
<h3>更新</h3>
<p>对于集合，有以下更新它自身的 Method：</p>
<p><strong>add</strong>(<em>elem</em>)</p>
<blockquote>
<p>把 elem 加入集合</p>
</blockquote>
<p><strong>remove</strong>(<em>elem</em>)</p>
<blockquote>
<p>从集合中删除 elem；如果集合中不包含该 elem，会产生 KeyError 错误。</p>
</blockquote>
<p><strong>discard</strong>(<em>elem</em>)</p>
<blockquote>
<p>如果该元素存在于集合中，删除它。</p>
</blockquote>
<p><strong>pop</strong>(<em>elem</em>)</p>
<blockquote>
<p>从集合中删除 elem，并返回 elem 的值，针对空集合做此操作会产生 KeyError 错误。</p>
</blockquote>
<p><strong>clear</strong>()
从集合中删除所有元素。</p>
<p><strong>set.update</strong>(*<em>others</em>)，相当于 <code>set |= other | ...</code></p>
<blockquote>
<p>更新 set, 加入 others 中的所有元素；</p>
</blockquote>
<p><strong>set.intersection_update</strong>(*<em>others</em>)，相当于 <code>set &amp;= other &amp; ...</code></p>
<blockquote>
<p>更新 set, 保留同时存在于 set 和所有 others 之中的元素；</p>
</blockquote>
<p><strong>set.difference_update</strong>(*<em>others</em>)，相当于 <code>set -= other | ...</code></p>
<blockquote>
<p>更新 set, 删除所有在 others 中存在的元素；</p>
</blockquote>
<p><strong>set.symmetric_difference_update</strong>(<em>other</em>)，相当于 <code>set ^= other</code></p>
<blockquote>
<p>更新 set, 只保留存在于 set 或 other 中的元素，但不保留同时存在于 set 和 other 中的元素；<strong>注意</strong>，该 Method <em>只接收一个参数</em>。</p>
</blockquote>
<h3>冻结集合</h3>
<p>还有一种集合，叫做冻结集合（Frozen Set），Frozen Set 之于 Set，正如 Tuple 之于 List，前者是不可变容器（Immutable），后者是可变容器（Mutable），无非是为了节省内存使用而设计的类别。</p>
<p>有空去看看这个链接就可以了：</p>
<blockquote>
<p>https://docs.python.org/3/library/stdtypes.html#frozenset</p>
</blockquote>
<h2>字典（Dictionary）</h2>
<p>Map 是容器中的单独一类，<strong>映射</strong>（Map）容器。映射容器只有一种，叫做<strong>字典</strong>（Dictionary）。先看一个例子：</p>
<div class="highlight"><pre><span></span><span class="n">phonebook</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">}</span>
<span class="n">phonebook</span>
</pre></div>


<p>字典里的每个元素，由两部分组成，<em>key</em>（键）和 <em>value</em>（值），二者由一个冒号连接。</p>
<p>比如，<code>'ann':6575</code> 这个字典元素，<em>key</em> 是 <code>'ann'</code>，<em>value</em> 是 <code>6575</code>。</p>
<p>字典直接使用 <em>key</em> 作为索引，并映射到与它匹配的 <em>value</em>：</p>
<div class="highlight"><pre><span></span><span class="n">phonebook</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">}</span>
<span class="n">phonebook</span><span class="p">[</span><span class="s1">&#39;bob&#39;</span><span class="p">]</span>
</pre></div>


<div class="highlight"><pre><span></span>8982
</pre></div>


<p>在同一个字典里，<em>key</em> 都是唯一的。当创建字典的时候，如果其中有重复的 <em>key</em> 的话，就跟 Set 那样会 “<strong>自动去重</strong>” —— 保留的是众多重复的 <em>key</em> 中的最后一个 <em>key:value</em>（或者说，最后一个 <em>key:value</em> “之前那个 <em>key</em> 的 <em>value</em> 被<strong>更新</strong>了”)。字典这个数据类型之所以叫做 Map（映射），是因为字典里的 <em>key</em> 都映射且只映射一个对应的 <em>value</em>。</p>
<div class="highlight"><pre><span></span><span class="n">phonebook</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>
<span class="n">phonebook</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;ann&#39;: 6585, &#39;bob&#39;: 8982, &#39;joe&#39;: 2598, &#39;zoe&#39;: 1225}
</pre></div>


<p>在已经了解如何操作列表之后，再去理解字典的操作，其实没什么难度，无非就是字典多了几个 Methods。</p>
<p>提蓄一下自己的耐心，把下面的若干行代码都仔细阅读一下，猜一猜输出结果都是什么？</p>
<h3>字典的生成</h3>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">aDict</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">bDict</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">:</span><span class="mi">3</span><span class="p">}</span>
<span class="n">aDict</span>
<span class="n">bDict</span>
</pre></div>


<div class="highlight"><pre><span></span>{}
{&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}
</pre></div>


<h3>更新某个元素</h3>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>

<span class="n">phonebook1</span><span class="p">[</span><span class="s1">&#39;joe&#39;</span><span class="p">]</span>
<span class="n">phonebook1</span><span class="p">[</span><span class="s1">&#39;joe&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5802</span>
<span class="n">phonebook1</span>
<span class="n">phonebook1</span><span class="p">[</span><span class="s1">&#39;joe&#39;</span><span class="p">]</span>
</pre></div>


<div class="highlight"><pre><span></span>2598
{&#39;ann&#39;: 6585, &#39;bob&#39;: 8982, &#39;joe&#39;: 5802, &#39;zoe&#39;: 1225}
5802
</pre></div>


<h3>添加元素</h3>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>
<span class="n">phonebook2</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;john&#39;</span><span class="p">:</span><span class="mi">9876</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">:</span><span class="mi">5603</span><span class="p">,</span> <span class="s1">&#39;stan&#39;</span><span class="p">:</span><span class="mi">6898</span><span class="p">,</span> <span class="s1">&#39;eric&#39;</span><span class="p">:</span><span class="mi">7898</span><span class="p">}</span>

<span class="n">phonebook1</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">phonebook2</span><span class="p">)</span>
<span class="n">phonebook1</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;ann&#39;: 6585,
 &#39;bob&#39;: 8982,
 &#39;joe&#39;: 2598,
 &#39;zoe&#39;: 1225,
 &#39;john&#39;: 9876,
 &#39;mike&#39;: 5603,
 &#39;stan&#39;: 6898,
 &#39;eric&#39;: 7898}
</pre></div>


<h3>删除某个元素</h3>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>

<span class="k">del</span> <span class="n">phonebook1</span><span class="p">[</span><span class="s1">&#39;ann&#39;</span><span class="p">]</span>
<span class="n">phonebook1</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;bob&#39;: 8982, &#39;joe&#39;: 2598, &#39;zoe&#39;: 1225}
</pre></div>


<h3>逻辑操作符</h3>
<div class="highlight"><pre><span></span><span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>

<span class="s1">&#39;ann&#39;</span> <span class="ow">in</span> <span class="n">phonebook1</span>

<span class="n">phonebook1</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="s1">&#39;stan&#39;</span> <span class="ow">in</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>

<span class="n">phonebook1</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="mi">1225</span> <span class="ow">in</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>

<span class="n">phonebook1</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="p">(</span><span class="s1">&#39;stan&#39;</span><span class="p">,</span> <span class="mi">6898</span><span class="p">)</span> <span class="ow">in</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span>True
dict_keys([&#39;ann&#39;, &#39;bob&#39;, &#39;joe&#39;, &#39;zoe&#39;])
False
dict_values([6585, 8982, 2598, 1225])
True
dict_items([(&#39;ann&#39;, 6585), (&#39;bob&#39;, 8982), (&#39;joe&#39;, 2598), (&#39;zoe&#39;, 1225)])
False
</pre></div>


<h3>可用来操作的内建函数</h3>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>
<span class="n">phonebook2</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;john&#39;</span><span class="p">:</span><span class="mi">9876</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">:</span><span class="mi">5603</span><span class="p">,</span> <span class="s1">&#39;stan&#39;</span><span class="p">:</span><span class="mi">6898</span><span class="p">,</span> <span class="s1">&#39;eric&#39;</span><span class="p">:</span><span class="mi">7898</span><span class="p">}</span>
<span class="n">phonebook1</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">phonebook2</span><span class="p">)</span>

<span class="nb">len</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">max</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">min</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">list</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">tuple</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">set</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">sorted</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">)</span>
<span class="nb">sorted</span><span class="p">(</span><span class="n">phonebook1</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>8
&#39;zoe&#39;
&#39;ann&#39;
[&#39;ann&#39;, &#39;bob&#39;, &#39;joe&#39;, &#39;zoe&#39;, &#39;john&#39;, &#39;mike&#39;, &#39;stan&#39;, &#39;eric&#39;]
(&#39;ann&#39;, &#39;bob&#39;, &#39;joe&#39;, &#39;zoe&#39;, &#39;john&#39;, &#39;mike&#39;, &#39;stan&#39;, &#39;eric&#39;)
{&#39;ann&#39;, &#39;bob&#39;, &#39;eric&#39;, &#39;joe&#39;, &#39;john&#39;, &#39;mike&#39;, &#39;stan&#39;, &#39;zoe&#39;}
[&#39;ann&#39;, &#39;bob&#39;, &#39;eric&#39;, &#39;joe&#39;, &#39;john&#39;, &#39;mike&#39;, &#39;stan&#39;, &#39;zoe&#39;]
[&#39;zoe&#39;, &#39;stan&#39;, &#39;mike&#39;, &#39;john&#39;, &#39;joe&#39;, &#39;eric&#39;, &#39;bob&#39;, &#39;ann&#39;]
</pre></div>


<h3>常用 Methods</h3>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>
<span class="n">phonebook2</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;john&#39;</span><span class="p">:</span><span class="mi">9876</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">:</span><span class="mi">5603</span><span class="p">,</span> <span class="s1">&#39;stan&#39;</span><span class="p">:</span><span class="mi">6898</span><span class="p">,</span> <span class="s1">&#39;eric&#39;</span><span class="p">:</span><span class="mi">7898</span><span class="p">}</span>

<span class="n">phonebook3</span> <span class="o">=</span> <span class="n">phonebook2</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="n">phonebook3</span>

<span class="n">phonebook3</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="n">phonebook3</span>

<span class="n">phonebook2</span>                      <span class="c1"># .copy() 的 “原件” 不会发生变化</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">popitem</span><span class="p">()</span>
<span class="n">p</span>
<span class="n">phonebook1</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="s1">&#39;adam&#39;</span><span class="p">,</span> <span class="mi">3538</span><span class="p">)</span>
<span class="n">p</span>
<span class="n">phonebook1</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;adam&#39;</span><span class="p">,</span> <span class="mi">3538</span><span class="p">)</span>
<span class="n">p</span>
<span class="n">phonebook1</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="s1">&#39;adam&#39;</span><span class="p">,</span> <span class="mi">3538</span><span class="p">)</span>
<span class="n">p</span>
<span class="n">phonebook1</span>
</pre></div>


<div class="highlight"><pre><span></span>{&#39;john&#39;: 9876, &#39;mike&#39;: 5603, &#39;stan&#39;: 6898, &#39;eric&#39;: 7898}
{}
{&#39;john&#39;: 9876, &#39;mike&#39;: 5603, &#39;stan&#39;: 6898, &#39;eric&#39;: 7898}
(&#39;zoe&#39;, 1225)
{&#39;ann&#39;: 6585, &#39;bob&#39;: 8982, &#39;joe&#39;: 2598}
3538
{&#39;ann&#39;: 6585, &#39;bob&#39;: 8982, &#39;joe&#39;: 2598}
3538
{&#39;ann&#39;: 6585, &#39;bob&#39;: 8982, &#39;joe&#39;: 2598}
3538
{&#39;ann&#39;: 6585, &#39;bob&#39;: 8982, &#39;joe&#39;: 2598, &#39;adam&#39;: 3538}
</pre></div>


<h2>迭代各种容器中的元素</h2>
<p>我们总是有这样的需求：对容器中的元素逐一进行处理（运算）。这样的时候，我们就用 <code>for</code> 循环去迭代它们。</p>
<p>对于迭代 <code>range()</code> 和 <code>list</code> 中的元素我们已经很习惯了：</p>
<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0
1
2
</pre></div>


<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>1
2
3
</pre></div>


<h3>迭代的同时获取索引</h3>
<p>有时，我们想同时得到有序容器中的元素及其索引，那么可以调用 <code>enumerate()</code> 函数来帮我们：</p>
<div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">c</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 P
1 y
2 t
3 h
4 o
5 n
</pre></div>


<div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 0
1 1
2 2
</pre></div>


<div class="highlight"><pre><span></span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;ann&#39;</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">,</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">]</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">L</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">L</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">L</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 ann
1 bob
2 joe
3 john
4 mike
</pre></div>


<div class="highlight"><pre><span></span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;ann&#39;</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">,</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 ann
1 bob
2 joe
3 john
4 mike
</pre></div>


<h3>迭代前排序</h3>
<p>可以用 <code>sorted()</code> 和 <code>reversed()</code> 在迭代前先排好序：</p>
<div class="highlight"><pre><span></span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;bob&#39;</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">,</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">t</span><span class="p">)):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 ann
1 bob
2 joe
3 john
4 mike
</pre></div>


<div class="highlight"><pre><span></span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;bob&#39;</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">,</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 mike
1 john
2 joe
3 bob
4 ann
</pre></div>


<div class="highlight"><pre><span></span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;bob&#39;</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">,</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;mike&#39;</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">t</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">t</span><span class="p">)):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>0 joe
1 mike
2 john
3 ann
4 bob
</pre></div>


<h3>同时迭代多个容器</h3>
<p>可以在 <code>zip()</code> 这个函数的帮助下，同时迭代两个或者两个以上的容器中的元素（这样做的前提是，多个容器中的元素数量最好相同）：</p>
<div class="highlight"><pre><span></span><span class="n">chars</span> <span class="o">=</span> <span class="s1">&#39;abcdefghijklmnopqrstuvwxyz&#39;</span>
<span class="n">nums</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">27</span><span class="p">)</span>
<span class="k">for</span> <span class="n">c</span><span class="p">,</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">chars</span><span class="p">,</span> <span class="n">nums</span><span class="p">):</span>
    <span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s2">&quot;Let&#39;s assume {c} represents {n}.&quot;</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>Let&#39;s assume a represents 1.
Let&#39;s assume b represents 2.
Let&#39;s assume c represents 3.
Let&#39;s assume d represents 4.
Let&#39;s assume e represents 5.
Let&#39;s assume f represents 6.
Let&#39;s assume g represents 7.
Let&#39;s assume h represents 8.
Let&#39;s assume i represents 9.
Let&#39;s assume j represents 10.
Let&#39;s assume k represents 11.
Let&#39;s assume l represents 12.
Let&#39;s assume m represents 13.
Let&#39;s assume n represents 14.
Let&#39;s assume o represents 15.
Let&#39;s assume p represents 16.
Let&#39;s assume q represents 17.
Let&#39;s assume r represents 18.
Let&#39;s assume s represents 19.
Let&#39;s assume t represents 20.
Let&#39;s assume u represents 21.
Let&#39;s assume v represents 22.
Let&#39;s assume w represents 23.
Let&#39;s assume x represents 24.
Let&#39;s assume y represents 25.
Let&#39;s assume z represents 26.
</pre></div>


<h3>迭代字典中的元素</h3>
<div class="highlight"><pre><span></span><span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>

<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">phonebook1</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">phonebook1</span><span class="p">[</span><span class="n">key</span><span class="p">])</span>
</pre></div>


<div class="highlight"><pre><span></span>ann 6585
bob 8982
joe 2598
zoe 1225
</pre></div>


<div class="highlight"><pre><span></span><span class="n">phonebook1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6575</span><span class="p">,</span> <span class="s1">&#39;bob&#39;</span><span class="p">:</span><span class="mi">8982</span><span class="p">,</span> <span class="s1">&#39;joe&#39;</span><span class="p">:</span><span class="mi">2598</span><span class="p">,</span> <span class="s1">&#39;zoe&#39;</span><span class="p">:</span><span class="mi">1225</span><span class="p">,</span> <span class="s1">&#39;ann&#39;</span><span class="p">:</span><span class="mi">6585</span><span class="p">}</span>

<span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">phonebook1</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>ann 6585
bob 8982
joe 2598
zoe 1225
</pre></div>


<h2>总结</h2>
<p>这一章的内容，只不过是 “多” 而已，一旦逻辑关系理顺，就会觉得很简单。而这一章的开头，已经是最好的总结了。</p>
<p>最后需要补充的，只是两个参考链接，以后有什么搞不明白的地方，去那里翻翻就能找到答案：</p>
<blockquote>
<ul>
<li>https://docs.python.org/3/tutorial/datastructures.html#dictionaries</li>
<li>https://docs.python.org/3/library/stdtypes.html#typesmapping</li>
</ul>
</blockquote>
    </div><!-- /.entry-content -->

  </article>
</section>
        <section id="extras" class="body">
                <div class="blogroll">
                        <h2>blogroll</h2>
                        <ul>
                            <li><a href="http://getpelican.com/">Pelican</a></li>
                            <li><a href="http://python.org/">Python.org</a></li>
                            <li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
                            <li><a href="#">You can modify those links in your config file</a></li>
                        </ul>
                </div><!-- /.blogroll -->
                <div class="social">
                        <h2>social</h2>
                        <ul>

                            <li><a href="#">You can add links in your config file</a></li>
                            <li><a href="#">Another social link</a></li>
                        </ul>
                </div><!-- /.social -->
        </section><!-- /#extras -->

        <footer id="contentinfo" class="body">
                <p>Powered by <a href="http://www.maxiaoan.com/">Maxiaoan</a></p>
        </footer><!-- /#contentinfo -->

</body>
</html>